var http = require('http'),
    Q = require('q'),
    url = require('url'),
    _ = require('lodash'),
    qs = require('querystring');
var BaseFun = require('../../../BC/server/controllers/DataPush.server.controller');

/**
 * 调用U9服务并返回返回值
 * API : /api/barcodeinfo/postErp
 * 参数 ：
 * [option]：{path：url}；
 * [params]: {context: 上下文必须传, param1:param1, param2:param2}
 * [callBackFun]: 回调函数。参数为{ifsuccess: false/true, data: err}
 */
exports.post = function (option, params, callBackFun) {
    BaseFun.getERPParams(function (err, data) {
        if (err != null) {
            var rtnData = {
                ErrorMess: err,
                Ifsuccess: false
            }

            callBackFun && callBackFun(rtnData);
        }
        else {
            params = JSON.stringify(params);
            var tempUrl = '';
            if (data.ERPVirtualDir) {
                tempUrl = '/' + data.ERPVirtualDir;
            }
            tempUrl += '/' + option.url;

            var options = {
                hostname: data.ERPHostAddress,
                port: data.ERPPort,
                path: tempUrl,
                method: 'POST',
                json: true,
                headers: {
                    'Content-Type': 'application/json'
                }
            };

            var req = http.request(options, function (result) {
                result.setEncoding('utf8');

                //返回值,接受ERP系统返回内容
                var resultData = '';

                if (result.statusCode != '200') {
                    var rtnData = {};

                    //找不到连接
                    if (result.statusCode == '404') {
                        rtnData = {
                            ErrorMess: '调用ERP系统错误：' + result.statusMessage + '错误码：404！请检查URL是否正确',
                            Ifsuccess: false
                        }
                    } else if (result.statusCode == '500') {
                        rtnData = {
                            ErrorMess: '调用ERP系统错误：' + result.statusMessage + '错误码：500！请检查是否正常！',
                            Ifsuccess: false
                        }
                    } else {
                        rtnData = {
                            ErrorMess: '调用ERP系统错误：' + result.statusMessage + '错误码：' + result.statusCode,
                            Ifsuccess: false
                        }
                    }

                    callBackFun && callBackFun(rtnData);

                    return;
                }

                result.on('data', function (result) {
                    resultData += result;
                }).on('end', function () {
                    var rtnData = {};
                    var data = JSON.parse(resultData).d;

                    if (data) {
                        if (_.isArray(data)) {
                            //因为单个单据生成U9单据，所以结果取第一个
                            data = data[0];
                        }

                        if (data.IfSuccess) {
                            rtnData.IfSuccess = true;
                            if (data.DocID) { rtnData.DocID = data.DocID; }
                            if (data.BarCodeInfo) { rtnData.BarCodeInfo = data.BarCodeInfo; }
                            if (data.IfHaveRtnMess) { rtnData.IfHaveRtnMess = data.IfHaveRtnMess; }
                            if (data.Message) { rtnData.Message = data.Message; }
                        } else {
                            rtnData.IfSuccess = false;
                            rtnData.ErrorMess = '';

                            if (data.Message) { rtnData.ErrorMess += data.Message; }
                            if (data.ErrorMess) { rtnData.ErrorMess += data.ErrorMess; }
                            if (data.StackTrace) { rtnData.ErrorMess += "+堆栈：" + data.StackTrace; }
                        }
                    } else {
                        rtnData.IfSuccess = false;
                        rtnData.ErrorMess = '';

                        if (typeof (resultData) === 'string') {
                            rtnData.ErrorMess += resultData;
                        } else {
                            rtnData.ErrorMess += JSON.stringify(resultData);
                        }
                    }

                    callBackFun && callBackFun(rtnData);
                })
            }).on('error', function (err) {
                var rtnData = {
                    ErrorMess: err,
                    Ifsuccess: false
                }

                callBackFun && callBackFun(rtnData)
            })

            req.write(params);
            req.end();
        }
    });
}